package org.mifos.boss.webservice.RESTclient;

import java.io.IOException;

import org.apache.commons.httpclient.Cookie;
import org.apache.commons.httpclient.Credentials;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpState;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.apache.commons.logging.Log;
import org.apache.log4j.Logger;
import org.mifos.boss.ui.controller.BossCollectionController;

import com.mysql.jdbc.PreparedStatement;

public class RESTClient {
	
	public static String URL = "http://localhost:8080/mifos";

	static Logger logger = Logger.getLogger(RESTClient.class);
	public HttpClient httpConn;
	
	private GetMethod get = null;
	private PostMethod post= null;
	private int httpRes = 0;
	private String responseBody = null;
	
	private String username;
	private String password;
	
	public RESTClient(String username, String password){
		this.username = username;
		this.password = password;
		
		
	}

//  public static void main(String args[]) throws Exception {

//   GetMethod method = new GetMethod("http://localhost:8080/mifos");
//    try{
//      client.executeMethod(method);
//       Cookie[] cookies = client.getState().getCookies();
//      for (int i = 0; i < cookies.length; i++) {
//        Cookie cookie = cookies[i];
//        System.err.println(
//          "Cookie: " + cookie.getName() +
//          ", Value: " + cookie.getValue() +
//          ", IsPersistent?: " + cookie.isPersistent() +
//          ", Expiry Date: " + cookie.getExpiryDate() +
//          ", Comment: " + cookie.getComment());
//
//	  RESTClient cps = new RESTClient("mifos", "testmifos");
//	  cps.prepareConnection();
//	  cps.callRESTWithRequestMethodGet(URL+"/admin/system/id-information.json");
//	  
//	  
//	}
//  
//  public String callRESTAdmin () throws HttpException, IOException{
//	 
//	  get = new GetMethod(URL+"/admin/system/id-information.json");
//	  httpRes = httpConn.executeMethod(get);
//		logger.debug("Respnse code for callRESTSystemInformation : " + httpRes);
//		responseBody = get.getResponseBodyAsString();
//		System.out.println("========\n" + responseBody + "\n==========");
//		
//		return responseBody;
//	}
//  
  //get center by number
  // url : center/num-{globalCustNum}

  
  public void callRESTClient(){
	  
  }
  
  public String callRESTWithRequestMethodGet(String url) {
	  
	  get = new GetMethod(url);
	  
	  try {
		
		  httpRes = httpConn.executeMethod(get);
		 
		  logger.debug("Response code for "+url+ " : " + httpRes);
		  
		  responseBody = get.getResponseBodyAsString();
	
	  } catch (HttpException e) {
		  
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (IOException e) {
		
		// TODO Auto-generated catch block
		e.printStackTrace();
	} finally{
		  get.releaseConnection();
	  }
	  
	  System.out.println("========\n" + responseBody + "\n==========");    
	return responseBody;
	  
  }
  
  public String callRESTWithRequestMethodPost(String url){
	  post = new PostMethod(url);
	  
	  try {
		
		  httpRes = httpConn.executeMethod(post);
		 
		  logger.debug("Response code for "+url+ " : " + httpRes);
		  
		  responseBody = post.getResponseBodyAsString();
	
	  } catch (HttpException e) {
		  
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (IOException e) {
		
		// TODO Auto-generated catch block
		e.printStackTrace();
	} finally{
		  post.releaseConnection();
	  }
	    
	  
	  return responseBody;
  }
  
  
  public HttpClient prepareConnection() throws HttpException, IOException{
	  
	  	logger.debug("Establishing http session with mifos");

	  	httpConn = new HttpClient();

		Credentials credentials = new UsernamePasswordCredentials(username,password);
		
		httpConn.getParams().setAuthenticationPreemptive(true);
		httpConn.getState().setCredentials(AuthScope.ANY, credentials);
		
		HttpConnectionManagerParams conpar = new HttpConnectionManagerParams();
		conpar.setConnectionTimeout(5 * 60000); // 5 minutes
		conpar.setSoTimeout(5 * 60000); // 5 minutes
		httpConn.getHttpConnectionManager().setParams(conpar);
		
		GetMethod get = new GetMethod(URL);
		get.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
		get.setDoAuthentication(true);
		httpConn.executeMethod(get);
		
		String responseBody = get.getResponseBodyAsString();
		if (responseBody.contains("j_spring_security_check")) {
			
//			NameValuePair[] data = new NameValuePair[2];
//			data[0] = new NameValuePair("j_username", username);
//			data[1] = new NameValuePair("j_password", password);
			
			String loginUrl = URL + "/j_spring_security_check?j_username="+username+"&j_password="+password;
//			while (loginUrl.length() > 0
//					&& loginUrl.charAt(loginUrl.length() - 1) == '/') {
//				loginUrl = loginUrl.substring(0, loginUrl.length() - 1);
//			}
			PostMethod authpost = new PostMethod(loginUrl);

			// Release Get Connection
			get.releaseConnection();
		

			httpRes = httpConn.executeMethod(authpost);
			responseBody = authpost.getResponseBodyAsString();
			if (httpRes == 301 || httpRes == 302 || httpRes == 307) {
				// redirected, get content page
				get = new GetMethod(authpost.getResponseHeader("Location")
						.getValue());
				System.out.println(authpost.getResponseHeader("Location")
						.getValue());
				get.setRequestHeader("Content-Type",
						"text/plain; charset=UTF-8");
				authpost.releaseConnection();
				httpRes = httpConn.executeMethod(get);
				responseBody = get.getResponseBodyAsString();
			
				
				
				get.releaseConnection();
				
			}
		} else {
			get.releaseConnection();
		}

		return httpConn;
	  
  }

}
